﻿package Interface
{
	import Core.Game;
	import Core.InterfacePage;	
	
	import Interface.Top100Classes.TopLabel;
	import Interface.Top100Classes.TopContainer;
	import Interface.Top100Classes.TopScroller;
	
	import GameUtils.GameDataEvent;
	
	import flash.events.Event;
	import flash.text.TextField;
	import flash.events.MouseEvent;
	import flash.net.navigateToURL;
	import flash.net.URLRequest;
		
	public class PageTop100 extends InterfacePage
	{
		private var FLabels:Array;
		private var FScroller:TopScroller;
		private var FLoadingText:TextField;
		
		public function PageTop100():void
		{		
			FLoadingText = getChildByName('LoadingText') as TextField;
			FScroller = getChildByName('TopListSroller') as TopScroller;
			FLabels = new Array();
		}
		
		override public function set GameCore(AGame:Game):void
		{
			super.GameCore = AGame;			
			FGame.MySQL.addEventListener(FGame.MySQL.PLAYER_INFO_LOADED, OnPlayerInfoLoaded);
		}
		
		private function OnPlayerInfoLoaded(e:GameDataEvent):void
		{
			FGame.MySQL.removeEventListener(FGame.MySQL.PLAYER_INFO_LOADED, OnPlayerInfoLoaded);
			FGame.MySQL.addEventListener(FGame.MySQL.PROFILES_LOADED, OnProfilesLoaded);
			FGame.MySQL.LoadTop100();
		}
		
		private function OnProfilesLoaded(e:GameDataEvent):void
		{
			FGame.MySQL.removeEventListener(FGame.MySQL.PROFILES_LOADED, OnProfilesLoaded);
			
			var vList:XMLList = new XMLList();
			vList = XML(e.Data).descendants('player');
			
			var vLabel:TopLabel;
			
			for (var i in vList)
			{
				with(vList[i])								
					vLabel = new TopLabel(@uid, @name, @rating);
				vLabel.addEventListener(MouseEvent.MOUSE_DOWN, OnLabelClick);
				FLabels.push(vLabel);
			} 
			
			AddLabels();
		}
		
		private function AddLabels():void
		{
			FLoadingText.visible = false;
			
			for(var i in FLabels)
			{
				TopLabel(FLabels[i]).Place = i + 1;
				FScroller.Add(TopLabel(FLabels[i]));
			}
		}
		
		public function Update():void
		{
			FLoadingText.visible = true;
			FScroller.Clear();
			FLabels = new Array();
			FGame.MySQL.addEventListener(FGame.MySQL.PROFILES_LOADED, OnProfilesLoaded);
			FGame.MySQL.LoadTop100();
		}
		
		private function OnLabelClick(e:MouseEvent):void
		{
			navigateToURL(new URLRequest('http://vkontakte.ru/id' + (e.target.parent as TopLabel).UID), '_blank');
		}
	}	
}
